//! # 性能监控警报系统
//! 
//! 本模块提供了RustCloud框架的性能监控警报系统实现。

use crate::performance_monitor::traits::*;
use serde::{Serialize, Deserialize};

/// 性能摘要
#[derive(Debug, Default, Serialize, Deserialize)]
pub struct PerformanceSummary {
    /// 运行时间（秒）
    pub uptime_seconds: u64,
    /// 平均CPU使用率
    pub avg_cpu_usage: f64,
    /// 最大CPU使用率
    pub max_cpu_usage: f64,
    /// 平均内存使用率
    pub avg_memory_usage: f64,
    /// 最大内存使用率
    pub max_memory_usage: f64,
    /// 总警报数
    pub total_alerts: usize,
    /// 警告级别警报数
    pub warning_alerts: usize,
    /// 严重级别警报数
    pub critical_alerts: usize,
    /// 数据点数量
    pub data_points: usize,
}

/// 警报处理器trait
#[async_trait::async_trait]
pub trait AlertHandler: Send + Sync {
    /// 处理警报
    async fn handle_alert(&self, alert: &PerformanceAlert) -> ServiceResult<()>;
    
    /// 获取处理器名称
    fn name(&self) -> &str;
}

/// 日志警报处理器
pub struct LoggingAlertHandler;

#[async_trait::async_trait]
impl AlertHandler for LoggingAlertHandler {
    async fn handle_alert(&self, alert: &PerformanceAlert) -> ServiceResult<()> {
        match alert.level {
            AlertLevel::Info => {
                tracing::info!("性能警报: {} - {}", alert.alert_type, alert.message);
            },
            AlertLevel::Warning => {
                tracing::warn!("性能警报: {} - {}", alert.alert_type, alert.message);
            },
            AlertLevel::Critical => {
                tracing::error!("性能警报: {} - {}", alert.alert_type, alert.message);
            },
        }
        Ok(())
    }

    fn name(&self) -> &str {
        "logging"
    }
}

/// 回调警报处理器
pub struct CallbackAlertHandler<F>
where
    F: Fn(&PerformanceAlert) -> ServiceResult<()> + Send + Sync,
{
    callback: F,
    name: String,
}

impl<F> CallbackAlertHandler<F>
where
    F: Fn(&PerformanceAlert) -> ServiceResult<()> + Send + Sync,
{
    pub fn new(name: String, callback: F) -> Self {
        Self { name, callback }
    }
}

#[async_trait::async_trait]
impl<F> AlertHandler for CallbackAlertHandler<F>
where
    F: Fn(&PerformanceAlert) -> ServiceResult<()> + Send + Sync,
{
    async fn handle_alert(&self, alert: &PerformanceAlert) -> ServiceResult<()> {
        (self.callback)(alert)
    }

    fn name(&self) -> &str {
        &self.name
    }
}